/*
  This piece of code should be compiled by
  ~sdcc~ compiler. If you use Keil or other
  compiler, there may be errors.

  (However it could be fixed by changing the
  header file and the way the register write.
  But I don't have Windows machine, so I
  could not test on it. )

  To compile:
    > sdcc play_sound.c

  To upload program:
    > stcgal -P stc89 -p <your-device> play_sound.ihx

  To see <your-device>:
    > ls /dev/tty.*
 */

#include "8052.h"

// the beeper on my machine is P25
// you have to change by your machine
// you can see the fig at ../../pic/STC89C52RC.jpg
#define BEEPER P2_5

// Note: the frequency is not correct
// I have no ideas on music
#define NOTE_A4 22
#define NOTE_B4 20
#define NOTE_C5 19
#define NOTE_D5 25

// the default KEY is high
#define KEY_1 !P3_1
#define KEY_2 !P3_0
#define KEY_3 !P3_2
#define KEY_4 !P3_3

void sleep(unsigned int time); // unit: millisecond
void play_sound(unsigned int t); // input period

void main() {
  while (1) { // endless loop
    if (KEY_1) { // if KEY_X is pressed down
      play_sound(NOTE_A4);
    }
    if (KEY_2) {
      play_sound(NOTE_B4);
    }
    if (KEY_3) {
      play_sound(NOTE_C5);
    }
    if (KEY_4) {
      play_sound(NOTE_D5);
    }
  }
}

void play_sound(unsigned int t) {
  BEEPER = 1;
  sleep(t);
  BEEPER = 0;
  sleep(t); 
}

void sleep(unsigned int time) { // millisecond
  while (time--) ;
}
